//
//  NRWSellCarInputInfoVC.m
//  NRWMall
//
//  Created by 张记 on 2018/5/25.
//  Copyright © 2018年 com.anpxd. All rights reserved.
//

#import "NRWSellCarInputInfoVC.h"
#import <SDCycleScrollView.h>
#import "UIImage+ImageCompress.h"
#import "NRWInputInfoCell.h"
#import "LRTranstionAnimationPush.h"
#import "LRTranstionAnimationPop.h"
#import "PickDateView.h"
#import "PickCityView.h"
#import "NRWBrandSeriesVC.h"
#import "NSString+Extension.h"
#import "NRWSellCarMessageModel.h"
#import "NRWBuyCarConditionModel.h"
#import "NRWSellCarInputApi.h"

@interface NRWSellCarInputInfoVC ()<UITableViewDelegate,UITableViewDataSource,SDCycleScrollViewDelegate,UINavigationControllerDelegate,PickerDateViewDelegate,PickerCityViewDelegate,UITextFieldDelegate,NRWBrandSeriesVCDelegate>
@property(nonatomic, strong) UITableView *tableview;
@property (nonatomic,strong) SDCycleScrollView *bannerView;
@property(nonatomic,strong)UIPercentDrivenInteractiveTransition *interactiveTransition;
@property (nonatomic, strong) UIButton *submitBtn;
@property (nonatomic, copy) NSString *dateStr;
@property (nonatomic, copy) NSString *adress;
@property (nonatomic, copy) NSString *previnceId;
@property (nonatomic, copy) NSString *cityId;
@property (nonatomic, strong)NRWSellCarMessageModel *model;
@property (copy, nonatomic) NRWBuyCarBrandModel *selectBrandModel;
@property (nonatomic, strong) NRWSellCarInputApi *inputMessageApi;
@end

@implementation NRWSellCarInputInfoVC
-(NRWSellCarInputApi *)inputMessageApi{
    if (!_inputMessageApi) {
        _inputMessageApi = [[NRWSellCarInputApi alloc] init];
        _inputMessageApi.delegate = self;
    }
    return _inputMessageApi;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationView setTitle:@"我要卖车"];
    [self initTableview];
    self.model = [[NRWSellCarMessageModel alloc] init];
    self.selectBrandModel = [[NRWBuyCarBrandModel alloc] init];
    UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [self.view addGestureRecognizer:gestureRecognizer];

}
- (void)handlePan:(UIPanGestureRecognizer *)gestureRecognizer {
    if ([gestureRecognizer translationInView:self.view].x>=20) {

        [self.navigationController popViewControllerAnimated:YES];
    }

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.delegate = self;
    
}
-(void)initTableview{
    kSelfWeak;
    self.tableview = [[UITableView alloc] init];
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.backgroundColor = backColor();
    [self.tableview registerClass:[NRWInputInfoCell class] forCellReuseIdentifier:@"NRWInputInfoCell"];
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).mas_offset(getNavHeight());
        make.left.right.bottom.equalTo(weakSelf.view);
    }];
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = false;
    }
    self.bannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH(), SCREEN_WIDTH() * 6 / 25) delegate:self placeholderImage:[UIImage imageNamed:@"banner"]];
    self.bannerView.currentPageDotImage = [UIImage imageWithColor:mainColor() forSize:CGSizeMake(15, 2)];
    self.bannerView.pageDotImage = [UIImage imageWithColor:[UIColor whiteColor] forSize:CGSizeMake(15, 2)];
    self.bannerView.localizationImageNamesGroup = @[@"sell_car_banner"];
    self.tableview.tableHeaderView = self.bannerView;
    UIView *footView = DPView();
    footView.frame = CGRectMake(0, 0, SCREEN_WIDTH(), 150);
    self.tableview.tableFooterView = footView;
    _submitBtn = [[UIButton alloc] init];
    [_submitBtn setTitle:@"提交" forState:UIControlStateNormal];
    [_submitBtn setTitleColor:whiteColor() forState:UIControlStateNormal];
    [_submitBtn setBackgroundImage:[UIImage imageNamed:@"submit_select_no"] forState:UIControlStateNormal];
    [_submitBtn addTarget:self action:@selector(submitInfo:) forControlEvents:UIControlEventTouchUpInside];
    _submitBtn.userInteractionEnabled = NO;
    [footView addSubview:self.submitBtn];
    [weakSelf.submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footView).mas_offset(23);
        make.right.equalTo(footView).mas_offset(-23);
        make.top.equalTo(footView).mas_equalTo(70);
        make.height.mas_equalTo(40);

    }];

}
//时间
-(void)CreatDateChoose{
    
    PickDateView *pickerDate = [[PickDateView alloc]init];
    
    pickerDate.pickerViewHeight = 300;
    [pickerDate setIsShowDay:NO];//是否显示日信息
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate* dt = [NSDate date];
    // 指定获取指定年、月、日、时、分、秒的信息
    unsigned unitFlags = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;
    NSDateComponents* comp = [gregorian components: unitFlags fromDate:dt];
    [pickerDate setDefaultTSelectYear:comp.year defaultSelectMonth:comp.month defaultSelectDay:comp.day];//设定默认显示的日期
    [pickerDate setDelegate:self];
    [pickerDate show];
}
-(void)pickerDateView:(BasePickView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day{
  
        _dateStr = [NSString stringWithFormat:@"%ld-%ld",year,month];
        NSString *today = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)year,month,day];

    NSDate *now = [NSDate date];
    if ([NRWCarTurnTime compareOneDay:now withAnotherDay:today] == 1 || [NRWCarTurnTime compareOneDay:now withAnotherDay:today] == 0 ) {
        _model.onTheCardTime = _dateStr;
    
    }else{
        
        [NRWMessageHUD showMessage:@"首次上牌时间不能比当前时间大" forTime:2.0 withRemindId:remindWarning];
        
        return ;
    }
    [self canSunmitMessage];
    [self.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    
}

//地址

-(void)chooseAdress{
    
    PickCityView *pickerArea = [[PickCityView alloc]init];
    pickerArea.pickerViewHeight = 300;
    [pickerArea setDelegate:self];
    //    [pickerArea setDefaultCity:@"北京" DefaultProvience:@"北京"];
    [pickerArea show];
    [self.view endEditing:YES];
}

-(void)pickerArea:(PickCityView *)pickerArea selectProvince:(NSString *)province selectCity:(NSString *)city{
    NSLog(@"省市的选择%@ %@",province,city);
    _model.city = [NSString stringWithFormat:@"%@",city];
    [self canSunmitMessage];
    [self.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    
}
-(void)pickerArea:(PickCityView *)pickerArea selectProvinceId:(NSString *)provinceId selectCityId:(NSString *)cityId{
    _model.cityId = cityId;
}
-(void)submitInfo:(UIButton *)sender{
    if ([_model.kilometre doubleValue] < 0.0001 || [_model.kilometre doubleValue] > 100.0) {
        [NRWMessageHUD showMessage:@"里程区间（0.0001 ~ 100.0）" forTime:2.0 withRemindId:remindWarning];
        return;
    }
 
    self.inputMessageApi.params = @{@"brandId":_model.brandId,
                                    @"brandName":_model.brandName,
                                    @"cityId":_model.cityId,
                                    @"cityName":_model.city,
                                    @"sellCarLicenceDate":_model.onTheCardTime,
                                    @"sellCarMileage":_model.kilometre,
                                    @"seriesId":_model.seriesId,
                                    @"seriesName":_model.seriesName,
                                    @"userId":[NRWUserInfoModel shared].userId
                                    };
    [self.inputMessageApi start];
    
    
}
#pragma mark - networkDelegate
- (void)requestFinished:(__kindof YTKBaseRequest *)request {
    if (request == self.inputMessageApi) {
        if ([request.responseObject[@"code"] isEqual:@1]) {
            
            [self.navigationController popViewControllerAnimated:YES];
            [NRWMessageHUD showMessage:@"提交成功,我们会尽快联系您" forTime:3.0 withRemindId:remindSuccess];
            self.inputCarSuccessful();
        }else{
            
            [NRWMessageHUD showMessage:request.responseObject[@"msg"] forTime:2.0 withRemindId:remindFail];
        }
    }
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request {
    
    [NRWMessageHUD showMessage:@"提交失败" forTime:2.0 withRemindId:remindFail];
}
#pragma mark - textfieldDelegateMethod
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if (textField.tag == 2) {
        if (isEmptyString(_model.onTheCardTime) == NO && isEmptyString(_model.city) == NO && isEmptyString(_model.brandId) == NO && isEmptyString(_model.seriesId) == NO) {
            self.submitBtn.userInteractionEnabled = YES;
            [_submitBtn setBackgroundImage:[UIImage imageNamed:@"submit_select_yes"] forState:UIControlStateNormal];
            
        }
        if ([DataCheck isLegalHXAccountCharacter:string] == NO) {
            if (string.length == 0 ){
                _model.kilometre = text;
                return YES;
            }
            return [DataCheck isLegalHXAccountCharacter:string];
        }
        if ([text returnRealWithFloatLength:4] == YES) {
            _model.kilometre = text;
        }
        return [text returnRealWithFloatLength:4];
    }
    return YES;
}
#pragma mark - DelegateMethod
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NRWInputInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NRWInputInfoCell" forIndexPath:indexPath];
    cell.inputF.tag = indexPath.row;
    cell.inputF.delegate = self;
    cell.index = indexPath;
    if (indexPath.row == 0) {
        cell.inputF.text = _model.brand;
    }else if (indexPath.row == 1){
        cell.inputF.text = _model.onTheCardTime;
    }else if (indexPath.row == 2){
        
    }else if (indexPath.row == 3){
        cell.inputF.text = _model.city;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 55;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
    if (indexPath.row == 0) {
        NRWBrandSeriesVC *brandVC = [[NRWBrandSeriesVC alloc] init];
        brandVC.selectBrandModel = self.selectBrandModel;
        brandVC.delegate = self;
        [self.navigationController pushViewController:brandVC animated:YES];
    }else if (indexPath.row == 1){
        [self CreatDateChoose];
    }else if (indexPath.row == 2){

    }else if (indexPath.row == 3){
        [self chooseAdress];

    }

    
}
#pragma mark -NRWBrandSeriesVCDelegate
-(void)brandSeriesVC:(NRWBrandSeriesVC *)view selectBrandId:(NSString *)selectBrandId selectBrandName:(NSString *)selectBrandName selectSeriesId:(NSString *)selectSeriesId selectSeriesName:(NSString *)selectSeriesName{
    if (selectBrandId == nil || selectSeriesId == nil) {
        [NRWMessageHUD showMessage:@"请选择品牌车系" forTime:2.0 withRemindId:remindWarning];
        return;
    }
    _model.brandName = self.selectBrandModel.brandName = selectBrandName;
    _model.brandId = self.selectBrandModel.brandId = selectBrandId;
    _model.seriesId = self.selectBrandModel.seriesId = selectSeriesId;
    _model.seriesName = self.selectBrandModel.seriesName = selectSeriesName;
    [self.tableview reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self canSunmitMessage];
   
}

-(void)canSunmitMessage{
    if (isEmptyString(_model.kilometre) == NO && isEmptyString(_model.onTheCardTime) == NO && isEmptyString(_model.city) == NO && isEmptyString(_model.brandId) == NO && isEmptyString(_model.seriesId) == NO) {
        self.submitBtn.userInteractionEnabled = YES;
        [_submitBtn setBackgroundImage:[UIImage imageNamed:@"submit_select_yes"] forState:UIControlStateNormal];
        
    }
}

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    
}
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index{
    
}
-(void)navigationViewLeftItemDidClick{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
}
//为这个动画添加用户交互
- (id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
                          interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController {
    return self.interactiveTransition;
}

#pragma mark -- UINavigationControllerDelegate --

- (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC{
    if (operation == UINavigationControllerOperationPop && [fromVC isKindOfClass:[NRWSellCarInputInfoVC class]]) {
        return [LRTranstionAnimationPop new];
    }else{
        return nil;
    }
}


@end
